
var xmlDoc;
function readKmlFile(path){

	if (window.XMLHttpRequest)
	  {// code for IE7+, Firefox, Chrome, Opera, Safari
	  	xmlhttp=new XMLHttpRequest();
	  	// xmlhttp.open("GET","/theme/Technology/map.kml",false);
	  	xmlhttp.open("GET",path,false);
		xmlhttp.send();
		xmlDoc=xmlhttp.responseXML;

		// console.log(xmlDoc);
		$("#root").html(setListMarkersKml())
		
	  }
}

function setListMarkersKml(){
	var div= '';
	folders = xmlDoc.getElementsByTagName('Folder');
	//xmlDoc.getElementsByTagName('Folder')[0].childNodes[1].childNodes[0].nodeValue;
	for(var i=0; i< folders.length; i++){
		if(folders[i].childNodes[1].childNodes[0].nodeValue !='Untitled layer'){
			div = div+ '<div class="control-group ">'
						+'<label for="NodeTypeName" class="control-label">Tên danh mục '+(i+1)+'</label>'
						+'<div class="controls">'
						+'<input name="data['+i+'][NodeType][name]" type="text" '
							+' id="NodeTypeName" value="'+ folders[i].childNodes[1].childNodes[0].nodeValue+'" readonly>'
						+'<input name="data['+i+'][NodeType][enabled]" value="1" type="hidden" id="NodeTypeName"></div></div>'	;
			markersKml = folders[i].getElementsByTagName('Placemark');
			for(var j=0; j< markersKml.length; j++){
				coor =markersKml[j].childNodes[9];
				
				div= div + '<div class="control-group item-group">'
							+'<label for="NodeTitle" class="control-label">Tên điểm</label>'
							+'<div class="controls">'
							+'<input name="data['+i+'][Node]['+j+'][title]" value="'+$(markersKml[j].childNodes[3]).text()+'" type="text" id="NodeTitle" readonly>'
							+'</div></div>'
						 + '<div class="control-group item-group">'
							+'<label for="NodeTitle" class="control-label">Tọa độ</label>'
							+'<div class="controls">'
							+'<input name="data['+i+'][Node]['+j+'][field_latLng]" '
								+'value="'+$(coor).find('coordinates').text()+'" type="text" id="NodeTitle" readonly>'
							+'</div></div>'
							+'<input name="data['+i+'][Node]['+j+'][is_published]" '
								+'value="1" type="hidden" id="NodeTitle">';

			 	// 	div = div+ '<li class="'+ markersKml[j].childNodes[1].innerHTML.substr(1)+'">'
					// 	+ '<a href="#" data-latLng="'+ $(coor).find('coordinates').text()
					// 		+'" data-name="'+$(markersKml[j].childNodes[3]).text()+'">'
					// 			+$(markersKml[j].childNodes[3]).text()+'</a>' 
					// 	+ '</li>';
					// console.log($(markersKml[j].childNodes[3]).text());
				// }
			}
			div = div + '<div class="clearFixKML"></div>';
		}
	}
	return div;
}






$(document).ready(function(){
	
	//readKmlFile();
	$("#loadKmlBtn").click(function(e){
		e.preventDefault();
		path= $("#pathKml").val();
		console.log(path);
		if(path){
			if(path.indexOf('.kml') == (path.length - 4)){
				readKmlFile(path);	
			}else{
				alert("Vui lòng chọn file Kml");	
			}
			
		}else{
			alert("Vui lòng chọn file Kml");
		}
	})
});